<?php

namespace App\Supports\Auth\Wap;

use App\Models\User;
use App\Events\NewUserRegisteredEvent;

class WapLogger
{
	protected function getExistingUser($phone)
	{
		return User::query()->where('phone', $phone)->first();
	}
	
	protected function registerBySelf($phone)
	{
		$user = User::create([
			'grade' => 'normal',
			'phone' => trim($phone),
			'name' => trim($phone),
		]);
		
		event(new NewUserRegisteredEvent($user));
		
		return $user;
	}
	
	protected function registerByInviter($phone, $inviter)
	{
		$user = $inviter->children()->create([
			'grade' => 'normal',
			'phone' => trim($phone),
			'name' => trim($phone),
		]);
		
		event(new NewUserRegisteredEvent($user));
		
		return $user;
	}
	
	protected function signup($phone, $inviter = null)
	{
		if ($inviter) {
			return $this->registerByInviter($phone, $inviter);
		}
		return $this->registerBySelf($phone);
	}
	
	public function auth($phone, $inviter = null)
	{
		if ($user = $this->getExistingUser($phone)) {
			return $user;
		}
		return $this->signup($phone, $inviter);
	}
}
